using LuUpgrade.Model;
using LuUpgrade.Utils;
using SqlSugar;


namespace LuUpgrade.Controller
{
    public class DbOperate
    {
        private readonly SqlSugarClient _db = new DbContext().Db;

        public void Mige()
        {
            _db.CodeFirst.InitTables(typeof(EmployeeEntity), typeof(CompanyEntity));
        }

        public EmployeeEntity Get(int id)
        {
            return _db.Queryable<EmployeeEntity>().InSingle(id);
        }

        // 查询多条
        public List<EmployeeEntity> GetEmployeeList()
        {
            var ems = _db.Queryable<EmployeeEntity>().Take(10000).ToList();
            return ems;
        }


        public List<ServerEntity> GetServers()
        {
            return _db.Queryable<ServerEntity>().Take(100).ToList();
        }


        // 条件查询
        public ServerEntity? GetServer()
        {
            var server = _db.Queryable<ServerEntity>().Where(s => s.Name == "蜀山3服").First();
            if (server != null)
            {
                //Console.WriteLine($"查询成功，服务器ID: {server.Id}, 服务器名: {server.Name}, 地址: {server.GameAddr}");
                return server;
            }
            else
            {
                Console.WriteLine("未找到符合条件的用户");
            }

            return null;
        }

        public int AddOneEmployee(EmployeeEntity emp)
        {
            // 插入数据
            var id = _db.Insertable(emp).ExecuteReturnIdentity();
            return id;
        }

        // 更新数据
        public int UpdateEmployee(int id)
        {
            var res = _db.Updateable<EmployeeEntity>()
                .SetColumns(it => new EmployeeEntity
                    { Province = "河南省", Age = 22, Username = "大唐李白3", Created = DateTime.Now })
                .Where(it => it.Id == id)
                .ExecuteCommand();
            return res;
        }


        // 删除数据
        public int DeleteEmployee(int id)
        {
            var res = _db.Deleteable<EmployeeEntity>()
                .Where(it => it.Id == id)
                .ExecuteCommand();

            return res;
        }
    }
}